<?php
/**
 * 认证模块 后台
 *
 * @author    wangmx <wangmx@yunys.com.cn>
 * @copyright 2016 QuanZhouYunYiShang Inc.
 */
namespace App\Services\UserService;

use Illuminate\Http\Request;
use DB;
use App\Services\BrandService\BrandToolService;
use App\Services\ImgServices\ImgTool;
use App\Services\ProductsService\ProductTool;
use App\Services\Tool\Jpush\JpushTool;
use App\Services\SourcePicService\SourcePicTool;
use App\Services\Tool\ImageProcessor\ImagickTool as ImagickTool;
use App\Services\UserService\UserTool;
use Maatwebsite\Excel\Facades\Excel;


class authenticationBackstage
{
    protected $ProductsService;
    protected $UserTool;

    public function __construct(UserTool $UserTool, ProductTool $Product)
    {
        $this->UserTool = $UserTool;
        $this->Product = $Product;
    }

    /**
     * 设计师认证列表
     * state 0待审核 1已通过 2拒绝
     */
    public function AuthenticationToDesigner(Request $request)
    {
        $state = $request->get('state');
        if (strlen($state) == 0) {
            $lists = DB::table('designer_authentications')->orderBy('created_at', 'desc')->distinct()->paginate(10);
        } else if ($state == 3) {
            $lists = DB::table('designer_authentications')->where('is_commend', 1)->orderBy('commend_time', 'desc')->distinct()->paginate(10);
        } else {
            $lists = DB::table('designer_authentications')->where('state', $state)->orderBy('created_at', 'desc')->distinct()->paginate(10);
        }
        return $lists;
    }

    /**
     * 品牌认证列表
     * state 0待审核 1已通过 2拒绝
     */
    public function AuthenticationToBrand(Request $request)
    {
        $state = $request->get('state');
        if (strlen($state) == 0) {
            $lists = DB::table('brand_authentications')->orderBy('created_at', 'desc')->distinct()->paginate(10);
        } else if ($state == 3) {
            $lists = DB::table('brand_authentications')->where('is_commend', 1)->orderBy('commend_time', 'desc')->distinct()->paginate(10);
        } else {
            $lists = DB::table('brand_authentications')->where('state', $state)->orderBy('created_at', 'desc')->distinct()->paginate(10);
        }
        return $lists;
    }

    /**
     * 通过认证
     * authentication_type 1设计师 2品牌
     */
    public function passAuthentication(Request $request)
    {
        $authentication_type = $request->get('type');
        $user_id = $request->get('user_id');
        $message = '';
        $create_num = DB::table('products')->where([
            'user_id' => $user_id,
            'is_shelves' => 1,
            'state' => 1
        ])->count();
        if ($authentication_type == 1) {
            DB::table('designer_authentications')->where('user_id', $user_id)->update(
                [
                    'product_num' => $create_num,
                    'message' => '',
                    'pass_time' => time(),
                    'state' => 1,
                    'updated_at' => time()
                ]
            );
            DB::table('users')->where('user_id', $user_id)->update(['user_type' => 1]);
            $hasBrand = DB::table('brand_authentications')->where('user_id', $user_id)->first();
            if ($hasBrand != null) {
                DB::table('brand_authentications')->where('user_id', $user_id)->delete();
            }
            $message = '【认证已通过】你已通过重重考验，正式加入设计师团队，系统功能已升级，赶快去看看吧~';
            $title = '认证已通过';
            $content = '你已通过了重重考验，正式加入设计师团队，系统功能已升级，赶快去看看吧~';
            $result = JpushTool::push($message, 0, $user_id,
                [
                    'title' => $title,
                    'user_id' => $user_id,
                    'class' => 'system_notification',
                    'type' => 1,
                    'jump_value' => '',
                    'template_no' => 2,
                    'message' => $content,
                    'images' => ['original_image' => '',
                        'thumbnail' => '']
                ]);

            $message1 = '设计师独门秘籍(若要修改认证信息，请联系客服)';
            JpushTool::push($message1, 0, $user_id,
                [
                    'title' => '认证消息',
                    'user_id' => $user_id,
                    'class' => 'system_notification',
                    'type' => 0,
                    //设计师独门秘籍H5 TODO
                    'jump_value' => 'http://www.mytee.cc',
                    'template_no' => 2,
                    'message' => $message1,
                    'images' => ['original_image' => '',
                        'thumbnail' => '']
                ]);
        } else if ($authentication_type == 2) {
            DB::table('brand_authentications')->where('user_id', $user_id)->update(
                [
                    'product_num' => $create_num,
                    'message' => '',
                    'pass_time' => time(),
                    'state' => 1,
                    'updated_at' => time()
                ]
            );
            DB::table('users')->where('user_id', $user_id)->update(['user_type' => 2]);
            $hasDesigner = DB::table('designer_authentications')->where('user_id', $user_id)->first();
            if ($hasDesigner != null) {
                DB::table('designer_authentications')->where('user_id', $user_id)->delete();
            }
            //品牌名 公司简称
            $brand_name = DB::table('brand_authentications')->where('user_id', $user_id)->value('company_abbreviation');
            $avatar = DB::table('users')->where('user_id', $user_id)->value('avatar');
            $BrandToolService = new BrandToolService();
            $data = array('user_id' => $user_id, 'brand_name' => $brand_name, 'avatar' => $avatar, 'state' => 1);
            $BrandToolService->syncBrandUser($data);//添加信息到品牌
            DB::table('users')->where('user_id', $user_id)->update(['nick_name' => $brand_name]);//将品牌简称同步到用户昵称
            $message = '【认证已通过】你已通过重重考验，正式加入品牌商团队，系统功能已升级，赶快去看看吧~';
            $title = '认证已通过';
            $content = '你已通过了重重考验，正式加入品牌商团队，系统功能已升级，赶快去看看吧~';
            $result = JpushTool::push($message, 0, $user_id,
                [
                    'title' => $title,
                    'user_id' => $user_id,
                    'class' => 'system_notification',
                    'type' => 1,
                    'jump_value' => '',
                    'template_no' => 2,
                    'message' => $content,
                    'images' => ['original_image' => '',
                        'thumbnail' => '']
                ]);
        }

        $result = array('message' => '', 'result' => (Object)array(), 'state' => 'M00000');
        return $result;
    }

    /**
     * 通过不认证
     * authentication_type 1设计师 2品牌
     * TODO 认证不通过时将已上架作品设置为下架
     */
    public function RefusedAuthentication(Request $request)
    {
        $authentication_type = $request->get('type');
        $user_id = $request->get('user_id');
        $message = $request->get('message');
        if ($authentication_type == 1) {
            DB::table('designer_authentications')->where('user_id', $user_id)->update(
                [
                    'message' => $message,
                    'state' => 2,
                    'is_commend' => 0,
                    'commend_time' => 0,
                    'is_index' => 0,
                    'updated_at' => time()
                ]
            );
            DB::table('users')->where('user_id', $user_id)->update(['user_type' => 0]);
        } else if ($authentication_type == 2) {
            DB::table('brand_authentications')->where('user_id', $user_id)->update(
                [
                    'message' => $message,
                    'state' => 2,
                    'is_commend' => 0,
                    'commend_time' => 0,
                    'is_index' => 0,
                    'updated_at' => time()
                ]
            );
            DB::table('users')->where('user_id', $user_id)->update(['user_type' => 0]);
//            $brand_name = DB::table('brand_authentications')->where('user_id', $user_id)->value('company_abbreviation');
//            $avatar = DB::table('users')->where('user_id', $user_id)->value('avatar');
//            $BrandToolService = new BrandToolService();
//            $data = array('user_id' => $user_id, 'brand_name' => $brand_name, 'avatar' => $avatar, 'state' => 0);
//            $BrandToolService->syncBrandUser($data);//添加信息到品牌
        }
        //上架商品,素材设为下架
        $this->Product->shelve_products_by_user_id($user_id);//商品
        SourcePicTool::offShelvesSourcePicByUserId($user_id);//素材
        $message = '【认证未通过】很遗憾，你的身份认证没能通过审核 ';

        $title = '认证未通过';
        $content = '很遗憾，你的认证申请没能通过审核';
        $result = JpushTool::push($message, 0, $user_id,
            [
                'title' => $title,
                'user_id' => $user_id,
                'class' => 'system_notification',
                'type' => 4,
                'jump_value' => '',
                'template_no' => 2,
                'message' => $content,
                'images' => ['original_image' => '',
                    'thumbnail' => '']
            ]);
        $result = array('message' => '', 'result' => (Object)array(), 'state' => 'M00000');
        return $result;
    }

    /**
     * 详情
     */
    public function detail($authentication_type, $user_id)
    {
        if ($authentication_type == 1) {
            $detail = DB::table('designer_authentications')->where('user_id', $user_id)->first();
            if ($detail == null) {
                return false;
            }
            $detail->front_card_url = asset('images/' . $detail->front_card_url);
            $detail->back_card_url = asset('images/' . $detail->back_card_url);
            $detail->create_img_url_1 = asset('images/' . $detail->create_img_url_1);
            $detail->create_img_url_2 = asset('images/' . $detail->create_img_url_2);
            $detail->create_img_url_3 = asset('images/' . $detail->create_img_url_3);

            return $detail;
        } else if ($authentication_type == 2) {
            $detail = DB::table('brand_authentications')->where('user_id', $user_id)->first();
            if ($detail == null) {
                return false;
            }
            $detail->front_card_url = asset('images/' . $detail->front_card_url);
            $detail->back_card_url = asset('images/' . $detail->back_card_url);
            $detail->business_license_url = asset('images/' . $detail->business_license_url);
            $detail->business_letters_url = asset('images/' . $detail->business_letters_url);
            return $detail;
        } else {
            return false;
        }
    }

    /**
     * 设置推荐
     */
    public function commend($authentication_type, $user_id)
    {
        if ($authentication_type == 1) {
            DB::table('designer_authentications')->where('user_id', $user_id)->update(
                [
                    'is_commend' => 1,
                    'commend_time' => time(),
                ]
            );
        } else if ($authentication_type == 2) {
            DB::table('brand_authentications')->where('user_id', $user_id)->update(
                [
                    'is_commend' => 1,
                    'commend_time' => time(),
                ]
            );
        }
        $result = array('message' => '', 'result' => (Object)array(), 'state' => 'M00000');
        return $result;
    }

    /**
     * 取消推荐
     */
    public function cancelCommend($authentication_type, $user_id)
    {
        if ($authentication_type == 1) {
            DB::table('designer_authentications')->where('user_id', $user_id)->update(
                [
                    'is_commend' => 0,
                    'commend_time' => 0,
                ]
            );
        } else if ($authentication_type == 2) {
            DB::table('brand_authentications')->where('user_id', $user_id)->update(
                [
                    'is_commend' => 0,
                    'commend_time' => 0,
                ]
            );
        }
        $result = array('message' => '', 'result' => (Object)array(), 'state' => 'M00000');
        return $result;
    }

    /**
     * 设置审核超时时间
     */
    public function updateTimeout($timeout)
    {
        DB::table('authentication_time_outs')->where('id', 1)->update(
            [
                'time_out' => $timeout,
                'updated_at' => time(),
            ]
        );
        $result = array('message' => '', 'result' => (Object)array(), 'state' => 'M00000');
        return $result;
    }

    /**
     * 修改设计师认证信息
     */
    public function editDesigner(Request $request)
    {
        $user_id = $request->get('user_id');
        $real_name = $request->get('real_name');
        $company = $request->get('company');
        $job = $request->get('job');
        $card_id = $request->get('card_id');
        $phone = $request->get('phone');
        $email = $request->get('email');
        DB::table('designer_authentications')->where('user_id', $user_id)->update(
            [
                'real_name' => $real_name,
                'company' => $company,
                'job' => $job,
                'card_id' => $card_id,
                'phone' => $phone,
                'email' => $email,
                'updated_at' => time(),
            ]
        );
        return true;
    }

    /**
     * 修改品牌认证信息
     */
    public function editBrand(Request $request)
    {
        $user_id = $request->get('user_id');
        $manager_name = $request->get('manager_name');
        $job = $request->get('job');
        $card_id = $request->get('card_id');
        $phone = $request->get('phone');
        $company_name = $request->get('company_name');
        $company_abbreviation = $request->get('company_abbreviation');
        DB::table('brand_authentications')->where('user_id', $user_id)->update(
            [
                'company_name' => $company_name,
                'company_abbreviation' => $company_abbreviation,
                'manager_name' => $manager_name,
                'job' => $job,
                'card_id' => $card_id,
                'phone' => $phone,
                'updated_at' => time(),
            ]
        );
        return true;
    }

    /**
     * 修改首页品牌LOGO
     */
    public function updateLogo(Request $request)
    {
        $logo = $request->file('logo');
        $user_id = $request->get('user_id');
        $ImgTool = new ImgTool(new ImagickTool());
        $logoPath = $ImgTool->imgSave($logo, 2);
        DB::table('brand_authentications')->where('user_id', $user_id)->update(
            [
                'logo' => $logoPath,
                'updated_at' => time(),
            ]
        );
        return true;
    }

    /**
     * 限制品牌名列表
     */
    public function limitNameList()
    {
        $lists = DB::table('company_name_limits')->orderBy('created_at', 'desc')->distinct()->paginate(10);
        return $lists;
    }

    /**
     * 删除限制品牌名
     */
    public function deleteLimit(Request $request)
    {
        $id = $request->get('id');
        DB::table('company_name_limits')->where('id', $id)->delete();
        $result = array('message' => '成功', 'result' => '', 'state' => 'M00000');
        return $result;
    }

    /**
     * 添加限制品牌名
     */
    public function addLimit(Request $request)
    {
        $name = $request->get('keyword');
        $check = DB::table('company_name_limits')->where('keyword', $name)->first();
        if ($check != null) {
            $result = array('message' => '失败', 'result' => '', 'state' => 'M00001');
            return $result;
        }
        DB::table('company_name_limits')->insert([
            'keyword' => $name,
            'created_at' => time(),
            'updated_at' => time(),
        ]);
        $result = array('message' => '成功', 'result' => '', 'state' => 'M00000');
        return $result;
    }

    /**
     * 编辑
     */
    public function editLimit(Request $request)
    {
        $name = $request->get('keyword');
        $id = $request->get('id');
        $check = DB::table('company_name_limits')->where('keyword', $name)->first();
        if ($check != null) {
            $result = array('message' => '失败', 'result' => '', 'state' => 'M00001');
            return $result;
        }
        DB::table('company_name_limits')->where('id', $id)->update([
            'keyword' => $name,
            'updated_at' => time(),
        ]);
        $result = array('message' => '成功', 'result' => '', 'state' => 'M00000');
        return $result;
    }

    public function VerifiedCard(Request $request)
    {
        $user_id = $request->get('user_id');
        $type = $request->get('type');
        $real_name = $request->get('real_name');
        $card_id = $request->get('card_id');
        $result = $this->UserTool->VerifiedCardBack($real_name, $card_id);
        if ($result['state'] == 'M00000') {
            switch ($type) {
                case 1:
                    DB::table('designer_authentications')->where('user_id', $user_id)->update(
                        ['id_card_state' => 1]
                    );
                    break;
                case 2:
                    DB::table('brand_authentications')->where('user_id', $user_id)->update(
                        ['id_card_state' => 1]
                    );
                    break;
            }
        }
        return $result;
    }


    public function updateDealer(Request $request)
    {
        $dealerId = $request->get('id');
        $dealerName = trim($request->get('dealer_name'));
        $dealerAddress = trim($request->get('dealer_area'));
        $dealerPhone = trim($request->get('dealer_phone'));
        DB::table('dealers')->where('id', $dealerId)->update(
            [
                'dealer_name' => $dealerName,
                'dealer_area' => $dealerAddress,
                'dealer_phone' => $dealerPhone,
                'updated_at' => time(),
            ]
        );
        $result = array('message' => '更新成功', 'result' => (Object)array(), 'state' => 'M00000');
        return $result;
    }

    /**
     * 经销商删除
     */
    public function deleteDealer(Request $request)
    {
        $dealerId = $request->get('id');
        DB::table('dealers')->where('id', $dealerId)->delete();
        $result = array('message' => '删除成功', 'result' => (Object)array(), 'state' => 'M00000');
        return $result;
    }


    /**
     * 限制词录入
     */
    public function loadExcel(Request $request)
    {
        $filePath = $request->file('ExcelFile');
        Excel::load($filePath, function ($reader) {
            //获取excel的第几张表
            $reader = $reader->getSheet(0);
            //获取表中的数据
            $results = $reader->toArray();
            //信息操作
            $count = count($results) - 1;
            DB::table('company_name_limits')->where('state', 1)->delete();
            for ($i = 1; $i <= $count; $i++) {
                $data = $results[$i];
                $keyword = strtolower($data[0]); //限制词
                DB::table('company_name_limits')->insert([
                    'keyword' => $keyword,
                    'state' => 1,
                    'created_at' => time(),
                    'updated_at' => time(),
                ]);
            }
        });
        $result = array('message' => '更新成功', 'result' => (Object)array(), 'state' => 'M00000');
        return $result;
    }
}